package com.nondo.rdp.finance.service.impl;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.core.domain.base.BaseEntity;
import com.nondo.rdp.finance.domain.Article;
import com.nondo.rdp.finance.repository.ArticleRepository;
import com.nondo.rdp.finance.service.ArticleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleRepository articleRepository;

    @Override
    public Article findOne(Long id) {
        return this.articleRepository.findOne(id);
    }

    @Override
    public Article save(Article article) {
        return this.articleRepository.save(article);
    }

    @Override
    public void delete(Long id) {
        this.articleRepository.deleteById(id);
    }

    @Override
    public Page<Article> findAll(Page<Article> page, Article article) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Article> dictPage = articleRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();

            //搜索标题
            if (StringUtils.isNotEmpty(article.getTitle())) {
                predicates.add(builder.like(root.get("title"), "%" + article.getTitle() + "%"));
            }

            //搜索ID
            if (article.getId() != null && article.getId() != 0) {
                predicates.add(builder.equal(root.get("id"), article.getId()));
            }
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<Article>(dictPage);
    }

    @Override
    public Article findByType(String type) {
        return this.articleRepository.findByTypeAndDelFlag(type, BaseEntity.DEL_FLAG_NORMAL);
    }
}